package com.heima.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.utils.AppJwtUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

@Autowired
private ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto dot) {
        //判断前端传进参数是不是为空
        if (dot==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断手机号和密码是否存在
        String phone = dot.getPhone();
        String password = dot.getPassword();
        if (StringUtils.isEmpty(phone)&&StringUtils.isEmpty(password)){
            //游客登录
            //生成token
            String token = AppJwtUtil.getToken(0L);
            //放进map集合返回
            HashMap<String, Object> map = new HashMap<>();
            map.put("user",null);
            map.put("token",token);
            return ResponseResult.okResult(map);

        }
        //正常登录
        //校验手机号存在
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone,phone);
        ApUser user = apUserMapper.selectOne(wrapper);
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //比对密码
        String salt = user.getSalt();
        String password1 = user.getPassword();
        String s = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!s.equals(password1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //生成token
        String token = AppJwtUtil.getToken(user.getId().longValue());
        //清除敏感数据
        user.setSalt("");
        user.setPassword("");

        HashMap<String, Object> map = new HashMap<>();
        map.put("user",user);
        map.put("token",token);

        //返回数据
           return ResponseResult.okResult(map);
    }








}